import pymysql
from pymysql import Error


def connect_mysql():
    """创建 MySQL 连接"""
    connection = None
    try:
        # 建立连接
        connection = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            password='r20050804.',
            database='zyg',  # 替换为你的数据库名
            charset='utf8mb4'
        )
        if connection.open:
            print("✅ 数据库连接成功！")
    except Error as e:
        print(f"❌ 连接失败：{e}")
    return connection


# 调用连接函数
conn = connect_mysql()

# 建立游标
cursor = conn.cursor()
cursor.execute("select * from book")
for row in cursor:
    print(row)
